jQuery(document).ready(function ($) {
    const $deleteCacheBtn = $("#cmc_delete_cache");
    const ajaxUrl = $deleteCacheBtn.data('ajax-url');
    const nonce = $deleteCacheBtn.data('cmc-nonce');

    $deleteCacheBtn.prop("disabled", false).on("click", function (e) {
        e.preventDefault();
        $(this).text('Purging...').prop("disabled", true);
        const requestData = {
            action: 'purge_transient_button',
            nonce: nonce
        };
        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: requestData,
            success: function (response) {
                if (response !== undefined && response.success == true) {
                    $deleteCacheBtn.text('Purged Cache').prop("disabled", true);
                }
            },
            error: function (error) {
                console.log(error);
            }
        });

    });


    const $liveupdate = $('#cmc_single_settings_live_updates');
    const $binance_url = $('.cmb2-id-cmc-binance-url');

    const $single_liveupdate = $('#single_live_updates');
    const $single_binance_url = $('.cmb2-id-cmc-single-binance-url');

    if ($liveupdate.length && $binance_url.length) {
        toggleBinanceSetting($liveupdate.is(':checked'), 'main');
        $liveupdate.on('change', function () {
            toggleBinanceSetting($(this).is(':checked'), 'main');
        });
    }


    if ($single_liveupdate.length && $single_binance_url.length) {
        toggleBinanceSetting($single_liveupdate.is(':checked'), 'single');

        $single_liveupdate.on('change', function () {
            toggleBinanceSetting($(this).is(':checked'), 'single');
        });
    }

    function toggleBinanceSetting(isChecked, type) {
        let $targetElement;
        if (type === 'main') {
            $targetElement = $binance_url;
        } else if (type === 'single') {
            $targetElement = $single_binance_url;
        }

        // Show or hide the target element
        if ($targetElement) {
            if (isChecked) {
                $targetElement.show();
            } else {
                $targetElement.hide();
            }
        }
    }

});